<?php
namespace Admin\Controller;

use Admin\Controller\GlobalController;

class PublicController extends GlobalController
{
    //预览手机上看到的简介页面和分享页面
    public function preview()
    {
        $suffix = '';
        if (isset($_GET['egg_id'])) {
            $id = I('get.egg_id', '', 'trim');
            $suffix = "?egg_id=$id";
        } elseif (isset($_GET['news_id'])) {
            $id = I('get.news_id', '', 'trim');
            $suffix = "?news_id=$id";
        } elseif (isset($_GET['spoiler_id'])) {
            $id = I('get.spoiler_id', '', 'trim');
            $suffix = "?spoiler_id=$id";
        }
        $this->assign('suffix', $suffix . '&debug=1');
        $this->display();
    }

    //图片在线缩略图
    public function thumb()
    {
        $offset = 86400;
        header("Pragma: cache");
        header("Expires: " . gmdate("D, d M Y H:i:s", time() + $offset) . " GMT");
        header("Cache-Control: max-age=$offset, must-revalidate");
        header("Content-type: image/jpeg");
        $image = I('get.image', '', 'trim');
        $image = WEB_PATH . '/www' . $image;

        //有缓存 直接取缓存图片
        $cache = S(md5($image));
        if ($cache) {
            exit(base64_decode($cache));
        }

        ob_start();
        $maxWidth = I('get.width', 99999, 'intval');
        $maxHeight = I('get.height', 99999, 'intval');

        // 获取原图信息
        $imageInfo = getimagesize($image);
        if ($imageInfo === false) {
            return false;
        }
        $srcWidth = abs($imageInfo[0]);
        $srcHeight = abs($imageInfo[1]);
        $type = strtolower(substr(image_type_to_extension($imageInfo[2]), 1));

        //xing393939修改
        $sw = 0;
        $sh = 0;
        // 计算缩放比例
        $scale = min($maxWidth / $srcWidth, $maxHeight / $srcHeight);
        $width = round($srcWidth * $scale);
        $height = round($srcHeight * $scale);

        // 载入原图
        $createFun = 'ImageCreateFrom' . ($type == 'jpg' ? 'jpeg' : $type);
        $srcImg = $createFun($image);

        //创建缩略图
        if ($type != 'gif')
            $thumbImg = imagecreatetruecolor($width, $height);
        else
            $thumbImg = imagecreate($width, $height);

        // 复制图片
        imagecopyresampled($thumbImg, $srcImg, 0, 0, $sw, $sh, $width, $height, $srcWidth, $srcHeight);
        if ('gif' == $type || 'png' == $type) {
            $background_color = imagecolorallocate($thumbImg, 0, 255, 0); //  指派一个绿色
            imagecolortransparent($thumbImg, $background_color); //  设置为透明色，若注释掉该行则输出绿色的图
        }

        // 对jpeg图形设置隔行扫描
        if ('jpg' == $type || 'jpeg' == $type)
            imageinterlace($thumbImg, 1);
        imagejpeg($thumbImg);
        imagedestroy($thumbImg);
        imagedestroy($srcImg);

        S(md5($image), chunk_split(base64_encode(ob_get_contents())), 864000);
    }
}